package com.cloudcc.cloudframe.net.async;

import android.content.Context;

import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.cloudframe.util.LogUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.loopj.android.http.SyncHttpClient;

public class AsyncClient {

	private static AsyncClient instance;
	private AsyncHttpClient client;
	private SyncHttpClient syncClient;//同步

	public AsyncClient() {
		super();
	}

	public synchronized static AsyncClient getInstance() {
		if (instance == null) {
			instance = new AsyncClient();
			instance.client = new AsyncHttpClient(true, 80, 443);
			instance.client.setTimeout(15*1000);
		}
		return instance;
	}

	public RequestHandle get(String url, RequestParams params,
			ResponseHandlerInterface responseHandler) {
		LogUtils.d("request", "网络请求:" + url + params.toString());
		return client.get(url, params, responseHandler);
	}
	/**
	 * get 请求
	 * @param url
	 * @param responseHandler
	 * @return
	 */
	public RequestHandle get(String url,ResponseHandlerInterface responseHandler) {
		return client.get(url,responseHandler);
	}

	public void get(Context context, String url, RequestParams params,
			ResponseHandlerInterface responseHandler) {
		client.get(context, url, params, responseHandler);
	}

	public RequestHandle post(String url, RequestParams params,
			ResponseHandlerInterface responseHandler) {
		LogUtils.d("request", "网络请求:" + url + params.toString());
		return client.post(url, params, responseHandler);
	}

	public void downFile(String url,
			FileAsyncHttpResponseHandler mFileAsyncHttpResponseHandler) {
		client.get(url, mFileAsyncHttpResponseHandler);
	}

	public AsyncHttpClient getClient() {
		return client;
	}
	
	/**
	 * 获得同步的 客户端
	 * @return
	 */
	public synchronized SyncHttpClient getSyncClient(){
		if (syncClient==null) {
			syncClient =new SyncHttpClient(80, 443);
		}
		return syncClient;
	}
	
	public void clear(Context context){
		if (client!=null) {
			PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
			myCookieStore.clear();
			client.setCookieStore(myCookieStore);
		}
	}

}
